package com.pb.poem.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.pb.poem.dao.BaseDao;
import com.pb.poem.dao.PoemDao;
import com.pb.poem.entity.Common;
import com.pb.poem.entity.Poem;

import com.pb.poem.entity.Words;

import com.pb.poem.util.ConfigManager;
import com.pb.poem.util.Page;

public class PoemDaoImpl extends BaseDao implements PoemDao {
	// 定义存储诗的单个字的集合
	private List<Words> poem = new ArrayList<Words>();
	// 定义存储诗的字符串
	private String poems = "";
	// 字的id
	private int wordId;
	// 标记诗是否包含词
	private boolean bl;

	// 将显示在页面上的诗，显示在数据库里
	@Override
	public boolean addPoem(Poem poem) {
		boolean flag = false;
		try {
			String sql = "insert into mypoem(poemname,author,content,date,uid)values(?,?,?,?,?)";
			Object[] params = { poem.getPoemname(), poem.getAuthor(),
					poem.getContent(), poem.getDate(), poem.getUid() };
			int i = this.executeupdate(sql, params);
			if (i > 0) {
				System.out.println("添加数据成功！！");
				flag = true;
			}
		} finally {
			this.closeResource();
		}
		return flag;
	}

	// 查询数据库里所有的诗
	@Override
	public List<Poem> getPoemsList() {
		String sql = "select * from mypoem order by date";
		Object params[] = {};
		return  getList(sql,params);
	}

	// 更新诗的内容
	@Override
	public boolean updatepoem(Poem poem) {
		boolean flag = false;
		try {
			String sql = "update mypoem  set poemname=?,author=?,date=?,content=? where id=? ";
			Object[] params = { poem.getPoemname(), poem.getAuthor(),
					poem.getDate(), poem.getContent(), poem.getId() };
			int i = this.executeupdate(sql, params);
			if (i > 0) {
				System.out.println("修改数据成功！！");
			}
			flag = true;
		} finally {
			this.closeResource();
		}
		return flag;
	}

	// 删除诗
	@Override
	public boolean delpoem(int id) {
		boolean flag = false;
		try {
			String sql = "delete from mypoem where id=? ";
			Object[] params = { id };
			int i = this.executeupdate(sql, params);
			if (i > 0) {
				System.out.println("删除数据成功！！");
			}
			flag = true;
		} finally {
			this.closeResource();
		}
		return flag;
	}

	// 根据Id值查询一首诗
	public List<Poem> getPoemById(String uid) {
		String sql = "select * from mypoem where uid=?";
		Object params[] = { uid };
		return  getList(sql,params);
	}

	/*
	 * @Override public Poem getPoemById(int id) { Poem poem=null; try{ String
	 * sql="select * from mypoem where id=?"; Object[] params={id}; ResultSet
	 * rs=this.executeSQL(sql, params); if(rs.next()){ String
	 * poemname=rs.getString("poemname"); String author=rs.getString("author");
	 * String content=rs.getString("content"); Date date=rs.getDate("date");
	 * poem=new Poem(); poem.setId(id); poem.setPoemname(poemname);
	 * poem.setAuthor(author); poem.setContent(content); poem.setDate(date);
	 * poem.setUid(rs.getString("uid")); } }catch(SQLException e){
	 * e.printStackTrace(); }finally{ this.closeResource(); } return poem; }
	 */
	// 添加评论
	@Override
	public int addCommon(Common common) {
		int pid = 0;
		try {
			String sql = "insert into comm(content,date,id)values(?,?,?);";
			Object[] params = { common.getContent(),
					new Timestamp(common.getDate().getTime()), common.getId() };
			// 增加数据
			pid = this.insertReturnId(sql, params);

		} finally {
			this.closeResource();
		}
		return pid;
	}

	// 查询评论信息
	@Override
	public List<Common> getCommonByid(int id) {
		List<Common> CommonList = new ArrayList<Common>();
		try {
			String sql = "select * from comm  where id=? order by pid";
			Object params[] = { id };
			ResultSet rs = this.executeSQL(sql, params);
			while (rs.next()) {
				int pid = rs.getInt("pid");
				String content = rs.getString("content");
				Timestamp date = rs.getTimestamp("date");
				Common common = new Common();
				common.setId(id);
				common.setPid(pid);
				common.setContent(content);
				common.setDate(date);
				// 将新闻对象返回集合中
				CommonList.add(common);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.closeResource();
		}
		return CommonList;
	}

	// 删除评论信息
	@Override
	public boolean delcommon(int pid) {
		boolean flag = false;
		try {
			String sql = "delete from comm where pid=?";
			Object[] params = { pid };
			int i = this.executeupdate(sql, params);
			if (i > 0) {
				System.out.println("删除数据成功！！");
			}
			flag = true;
		} finally {
			this.closeResource();
		}
		return flag;
	}

	// 得到总页数
	@Override
	public int getTotalProCount() {
		int totalCount = 0;
		String sql = "select count(*) from mypoem";
		Object[] params = {};
		ResultSet rs = this.executeSQL(sql, params);
		try {
			while (rs.next()) {
				totalCount = rs.getInt(1);// 实际拿到的结果
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			this.closeResource();
		}
		return totalCount;
	}

	// 分页获取全部的诗
	@Override
	public List<Poem> getPagePoemList(int id) {
		if(id==-1){
			id=Integer.MAX_VALUE;
		}
		int pageSize = Integer.parseInt(ConfigManager.getInstance().getString("pageSize"));
		
		String sql = "select * from mypoem where id<? order by id desc limit ?";
		Object[] params = new Object[] { id, pageSize };
		return getList(sql,params);
	}

	// 得到所有诗的个数
	@Override
	public int getallpoemcount() {
		// TODO Auto-generated method stub
		int totalCount = 0;
		String sql = "select count(*) from mypoem";
		Object[] params = {};
		ResultSet rs = this.executeSQL(sql, params);
		try {
			while (rs.next()) {
				totalCount = rs.getInt(1);// 实际拿到的结果
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			this.closeResource();
		}
		return totalCount;
	}

	// 得到某个人的诗个数
	@Override
	public int getonepoemcount(String author) {
		// TODO Auto-generated method stub
		int totalCount = 0;
		String sql = "select count(*) from mypoem where author=?";
		Object[] params = { author };
		ResultSet rs = this.executeSQL(sql, params);
		try {
			while (rs.next()) {
				totalCount = rs.getInt(1);// 实际拿到的结果
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			this.closeResource();
		}
		return totalCount;
	}

	/*
	 * 为个人生成的诗 分页
	 */
	// 得到某人生成诗的总个数
	@Override
	public int getonetotalProCount(String uid) {
		int totalCount = 0;
		String sql = "select count(*) from mypoem where uid=？";
		Object[] params = { uid };
		ResultSet rs = this.executeSQL(sql, params);
		try {
			while (rs.next()) {
				totalCount = rs.getInt(1);// 实际拿到的结果
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			this.closeResource();
		}
		return totalCount;
	}

	// 分页获取某用户的诗
	@Override
	public List<Poem> getonePagePoemList(int id, String uid) {
		if(id==-1){
			id=Integer.MAX_VALUE;
		}
		int pageSize = Integer.parseInt(ConfigManager.getInstance().getString("pageSize"));
		
		String	sql = "select * from mypoem where uid=? and id<? order by id desc limit ?";
		Object[]	params = new Object[] { uid, id, pageSize };
		return getList(sql,params);
	}

	// 查询某首诗的评论
	@Override
	public List<Common> getCommonsList(int id) {
		List<Common> CommonList = new ArrayList<Common>();
		try {
			String sql = "select * from comm  where id=? ";
			Object params[] = { id };
			ResultSet rs = this.executeSQL(sql, params);
			while (rs.next()) {
				int pid = rs.getInt("pid");
				String content = rs.getString("content");
				Timestamp date = rs.getTimestamp("date");
				Common common = new Common();
				common.setId(id);
				common.setPid(pid);
				common.setContent(content);
				common.setDate(date);
				// 将新闻对象返回集合中
				CommonList.add(common);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.closeResource();
		}
		return CommonList;
	}

	// 生成诗
	@Override
	public String create(String str) {
		// 获取平仄结构和意象id。
		int imageId;
		try {
			imageId = getImageId(str.substring(0, 1));
			// 使用循环依此生成每个字
			int[] frame = getFrame();
			for (int i = 0; i < frame.length; i++) {
				getNext(imageId, frame[i], i, wordId);
			}
			poems = poems.substring(0, 5) + "，" + poems.substring(5, 10)
					+ "。" + poems.substring(10, 15) + "，"
					+ poems.substring(15) + "。";
		} catch (SQLException e) {
			e.printStackTrace();
			return "对不起，请换关键字";
		} catch (Exception e) {
			System.err.println(e.getMessage());
			return "对不起，请换关键字";
		} finally {
			this.closeResource();
		}
		return poems;
	}

	/**
	 * 根据单个字获取意境的id
	 * 
	 * @param words
	 *            输入的字
	 * @return
	 * @throws Exception
	 */
	public int getImageId(String words) throws Exception {
		String sql = "select m.imageid,l.id from lexicon_2 l,middletable m where l.pword=? and l.id=m.pwordid ";
		ResultSet rs = this.executeSQL(sql, new String[] { words });
		int id = -1;
		List<Integer> list = new ArrayList<Integer>();
		while (rs.next()) {
			id = rs.getInt("imageid");
			list.add(id);
			wordId = rs.getInt("id");
		}
		if (list.size() == 0) {
			throw new Exception("没有符合的意象");
		}
		id = list.get((int) (Math.random() * list.size()));
		rs.close();
		return id;
	}

	/**
	 * 获取平仄结构
	 * 
	 * @return
	 */
	public int[] getFrame() {
		int[][] frame = {
				{ 1, 1, 2, 2, 1, 2, 2, 2, 1, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1 },
				{ 11, 22, 1, 22, 21, 1, 21, 11, 2, 11, 22, 1 },
				{ 11, 22, 1, 22, 21, 1, 22, 1, 12, 11, 2, 21 },
				{ 11, 2, 21, 22, 2, 11, 22, 11, 2, 11, 22, 1 },
				{ 11, 2, 21, 22, 2, 11, 22, 1, 12, 11, 2, 21 },

				{ 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1 },
				{ 11, 12, 2, 22, 21, 1, 22, 11, 2, 11, 22, 1 },
				{ 11, 12, 2, 22, 21, 1, 22, 1, 12, 11, 2, 21 },
				{ 11, 1, 22, 22, 2, 11, 22, 1, 12, 11, 2, 21 },
				{ 11, 1, 22, 22, 2, 11, 22, 11, 2, 11, 22, 1 },

				{ 2, 2, 2, 1, 1, 1, 1, 2, 2, 1, 2, 2, 2, 1, 1, 2, 2, 2, 1, 1 },
				{ 22, 21, 1, 11, 22, 1, 22, 21, 1, 22, 21, 1 },
				{ 22, 21, 1, 11, 22, 1, 22, 2, 11, 22, 2, 11 },
				{ 22, 2, 11, 11, 2, 21, 22, 21, 1, 22, 21, 1 },
				{ 22, 2, 11, 11, 2, 21, 22, 2, 11, 22, 2, 11 },

				{ 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2 },
				{ 22, 11, 2, 11, 22, 1, 11, 12, 2, 11, 12, 2 },
				{ 22, 11, 2, 11, 22, 1, 11, 1, 22, 11, 1, 22 },
				{ 22, 1, 12, 11, 2, 21, 11, 1, 22, 11, 1, 22 },
				{ 22, 1, 12, 11, 2, 21, 11, 12, 2, 11, 12, 2 } };
		int i = (int) (Math.random() * frame.length);
		if (frame[i].length < 20) {
			bl = true;
		}
		return frame[i];
	}

	/**
	 * 获取下一个字
	 * 
	 * @param imageId	意象id
	 * @param tonal		平仄
	 * @param index		字在诗中的位置
	 * @param pwordId	上一个字的id
	 * @throws Exception
	 */
	public void getNext(int imageId, int tonal, int index, int pwordId)
			throws Exception {
		String sql = null;
		// 拆分sql语句
		String s1 = "select l.id,l.pword,l.rhyme from lexicon_2 l ";
		String s2 = ",middletable m ";
		String s3 = ",wordsrank w ";

		String s4 = "where l.tone=? ";
		String s5 = "and l.rhyme=? ";
		String s6 = "and m.imageid=? and m.pwordid=l.id ";
		String s7 = "and w.words1=? and w.words2=l.id ";

		String s8 = "order by l.rate desc limit 15";
		String s9 = "order by w.rank desc,l.rate desc limit 15";

		ResultSet rs = null;
		int ri = 0;// 设置匹配的韵脚位置
		boolean flag = false;// 设置是否押韵的标志
		if (bl) {
			flag = (index + 1) % 6 == 0 ? true : false;
			ri = 2;
		} else {
			flag = (index + 1) % 10 == 0 ? true : false;
			ri = 4;
		}
		// 查询结果存入集合list
		List<Words> list = new ArrayList<Words>();
		for (int i = 0; list.size() == 0; i++) {//如果list长度为0，说明未找到匹配结果，接续循环
			if (i == 0) {//符合全部条件
				if (flag) {// 需要押韵
					sql = s1 + s2 + s3 + s4 + s5 + s6 + s7 + s9;
					rs = this.executeSQL(sql,
							new Integer[] { tonal, poem.get(ri).getRhyme(),
									imageId, pwordId });
				} else {// 不需要押韵
					sql = s1 + s2 + s3 + s4 + s6 + s7 + s9;
					rs = this.executeSQL(sql, new Integer[] { tonal, imageId,
							pwordId });
				}
			} else if (i == 1) {//去掉rank条件
				if (flag) {// 需要押韵
					sql = s1 + s2 + s4 + s5 + s6 + s8;
					rs = this.executeSQL(sql,
							new Integer[] { tonal, poem.get(ri).getRhyme(),
									imageId });
				} else {// 不需要押韵
					sql = s1 + s2 + s4 + s6 + s8;
					rs = this.executeSQL(sql, new Integer[] { tonal, imageId });
				}
			} else if (i == 2) {//去掉意境
				if (flag) {// 需要押韵
					sql = s1 + s4 + s5 + s8;
					rs = this.executeSQL(sql,
							new Integer[] { tonal, poem.get(ri).getRhyme() });
				} else {// 不需要押韵
					sql = s1 + s4 + s8;
					rs = this.executeSQL(sql, new Integer[] { tonal });
				}
			} else {
				throw new Exception("找不到匹配的词。");
			}
			while (rs.next()) {
				String w = rs.getString("pword");
//				// 判断诗中该字是否在同一位置重复出现
//				boolean f = false;// 判断标识
//				int k = bl ? 3 : 5;
//				for (int n = index - k; n >= 0; n = n - k) {
//					if (poem.get(n).getPword()
//							.endsWith(w.substring(w.length() - 1))) {
//						f = true;
//						break;
//					}
//				}
//				if (f) {
//					continue;
//				}
				//判断诗中是否出现过该词（以词为单位进行比较）
				if(poems.contains(w)){
					//System.out.println(poems+" , "+w);///////////////////////////
					continue;
				}
				//韵脚不能是同一个字
				if(flag){
					boolean f = false;// 判断标识
					int k = bl ? 3 : 5;
					String end=w.substring(w.length()-1);
					for(int in=index-k;in>0;in-=k){
						if(poem.get(in).getPword().endsWith(end)){
							f=true;
							break;
						}
					}
					if(f){
						continue;
					}
				}
				// 如果不重复，存入集合
				Words words = new Words(rs.getInt("id"), w, rs.getInt("rhyme"));
				list.add(words);

			}
			rs.close();
		}
		// 从集合list中随机选取一个词，存入集合poem
		int j = (int) (Math.random() * list.size());
		poem.add(list.get(j));
		poems += list.get(j).getPword();
		wordId = list.get(j).getId();
	}

	public static void main(String[] args) {
		PoemDaoImpl poemDao = new PoemDaoImpl();
		/*
		 * List<Poem> list=poemDao.getPagePoemList(2,1); for(Poem poem:list){
		 * System.out.println(poem.getId()+","+poem.getPoemname()); }
		 */
		/*
		 * List<Poem> list =poemDao.getPoemById("123"); for(Poem poem:list){
		 * System
		 * .out.println(poem.getId()+"\t"+poem.getContent()+"\t"+poem.getPoemname
		 * ()); }
		 */
	}
	/**
	 * 分页获取好友的诗
	 * @author Maocat
	 */
	@Override
	public List<Poem> getFriendPoems(int id, List<String> friendIds) {
		// TODO Auto-generated method stub
		int n=friendIds.size();
		if(n==0){
			//如果好友列表为空
			return new ArrayList<Poem>();
		}else{
			if(id==-1){
				id=Integer.MAX_VALUE;
			}
			int pageSize = Integer.parseInt(ConfigManager.getInstance().getString("pageSize"));//获取页码
			//根据好友列表长度，确定sql中占位符个数
			String fs="?";
			for(int i=1;i<n;i++){
				fs+=",?";
			}
			String sql = "select * from mypoem where id<? and uid in ("+fs+") order by id desc limit ?";
			Object[] params = new Object[n+2];
			params[0] =id;
			params[n+1]=pageSize;
			for(int j=0;j<n;j++){
				params[j+1]=friendIds.get(j);
			}
			return getList(sql,params);
		}
	}
	/**
	 * 获取诗列表通用方法
	 * @author Maocat
	 * @param sql
	 * @param params
	 * @return
	 */
	private List<Poem> getList(String sql,Object [] params){
		List<Poem> poemList = new ArrayList<Poem>();
		try {
			ResultSet rs = this.executeSQL(sql, params);
			while (rs.next()) {
				int pid = rs.getInt("id");
				String poemname = rs.getString("poemname");
				String author = rs.getString("author");
				String content = rs.getString("content");
				Date date = rs.getDate("date");
				Poem poem = new Poem();
				poem.setId(pid);
				poem.setPoemname(poemname);
				poem.setAuthor(author);
				poem.setContent(content);
				poem.setDate(date);
				poem.setUid(rs.getString("uid"));
				poemList.add(poem);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			this.closeResource();
		}
		return poemList;
	}

}
